// @Title  main
// @Description  
// @Author  EwdAger
// @Update  2021/9/26 19:15

package main

import (
    "fmt"
    "net"
    "net/http"
    "os"
    "time"
)

func sleep(w http.ResponseWriter, r *http.Request) {
    time.Sleep(10)

}

func health(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(200)
    _, err := fmt.Fprintf(w,"OK\r\n")
    if err != nil {
        return
    }
}

func getVersion(w http.ResponseWriter, r *http.Request) {

    // 系统里没有 VERSION 环境变量，用 GOPATH 代替
    ver := os.Getenv("GOPATH")
    w.Header().Add("GOPATH", ver)

}

func printHeader(w http.ResponseWriter, r *http.Request) {
    userIp := remoteIp(r)

    fmt.Println(userIp)
    _, err := fmt.Fprintf(w, userIp)
    if err != nil {
        return
    }

}

func remoteIp(req *http.Request) string {
    remoteAddr := req.RemoteAddr
    if ip := req.Header.Get("Remote_addr"); ip != "" {
        remoteAddr = ip
    } else {
        remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
    }

    if remoteAddr == "::1" {
        remoteAddr = "127.0.0.1"
    }
    return remoteAddr
}

func run() {
    http.HandleFunc("/healthz", health)
    http.HandleFunc("/getVersion", getVersion)
    http.HandleFunc("/printHeader", printHeader)
    err := http.ListenAndServe(":8000", nil)
    if err != nil {
        return
    }
}


func main() {
    run()
}
